﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using ProgNetComponents.Classes;
using System.ComponentModel.Design.Serialization;
using System.Reflection;

namespace ProgNetComponents.Design.TypeConverters
{
    /// <summary>
    /// NamedObjectTypeConverter
    /// </summary>
    public class NamedObjectTypeConverter : CollectionItemTypeConverter<NamedObject>
    {
        /// <summary>
        /// Determines whether this instance [can convert to] the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="destinationType">Type of the destination.</param>
        /// <returns></returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
                return true;
            return base.CanConvertTo(context, destinationType);
        }
        /// <summary>
        /// Converts to.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="culture">The culture.</param>
        /// <param name="value">The value.</param>
        /// <param name="destinationType">Type of the destination.</param>
        /// <returns></returns>
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
             NamedObject o = null;
             if (value is NamedObject)
                 o =  (value as NamedObject);
             if (o != null)
             {
                 if (destinationType == typeof(InstanceDescriptor))
                 {
                     ConstructorInfo ci = typeof(NamedObject).GetConstructor(new Type[] { typeof(string), typeof(object) });
                     if (ci != null)
                     {
                         return new InstanceDescriptor(ci, new object[] { o.Name, o.Value });
                     }
                 }
             }
            return base.ConvertTo(context, culture, value, destinationType);
        }

        /// <summary>
        /// Gets the constructor.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        protected override ConstructorInfo GetConstructor(NamedObject item)
        {
           return typeof(NamedObject).GetConstructor(new Type[] { typeof(string), typeof(object) });
        }

        /// <summary>
        /// Gets the constructor paramters.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        protected override object[] GetConstructorParamters(NamedObject item)
        {
            return new object[] { item.Name, item.Value };
        }
    }
}
